package com.wolf.gulimall.search.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.wolf.common.to.es.SkuEsModel;
import com.wolf.common.utils.R;
import com.wolf.gulimall.search.config.GuLiMallElasticSearchConfig;
import com.wolf.gulimall.search.constant.EsConstant;
import com.wolf.gulimall.search.feign.ProductFeignService;
import com.wolf.gulimall.search.service.MallSearchService;
import com.wolf.gulimall.search.vo.AttrResVo;
import com.wolf.gulimall.search.vo.SearchParam;
import com.wolf.gulimall.search.vo.SearchResult;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.validation.constraints.Null;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MallSearchServiceImpl implements MallSearchService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Autowired
    private ProductFeignService productFeignService;

    /**
     * 根据检索条件查询数据
     *
     * @param searchParam 检索条件
     * @return 查询的数据
     */
    @Override
    public SearchResult search(SearchParam searchParam) {
        //1.动态构建查询DSL语句
        SearchResult searchResult = null;
        //准备 检索请求
        SearchRequest searchRequest = buildSearchRequest(searchParam);

        try {
            //执行检索请求
            SearchResponse search = restHighLevelClient.search(searchRequest, GuLiMallElasticSearchConfig.COMMON_OPTIONS);
            //分析响应数据,封装成需要的数据
            searchResult = buildSearchResponse(search, searchParam);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return searchResult;
    }


    /**
     * 准备 检索请求
     *
     * @return 检索请求数据
     */
    private SearchRequest buildSearchRequest(SearchParam searchParam) {
        //DSL语句构造器
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        /**
         * 查询:模糊匹配，过滤（按照属性、分类、品牌，价格区间，库存）
         */
        //1.构建boolQueryBuilder
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //1.1 bool-must-模糊匹配
        if (!StringUtils.isEmpty(searchParam.getKeyWord())) {
            //根据sku标题查询
            boolQueryBuilder.must(QueryBuilders.matchQuery("skuTitle", searchParam.getKeyWord()));
        }
        //1.2 bool-filter - 过滤
        if (searchParam.getCatalog3Id() != null) {
            //根据三级分类ID进行过滤
            boolQueryBuilder.filter(QueryBuilders.termQuery("catalogId", searchParam.getCatalog3Id()));
        }
        //1.2 bool-filter - 过滤
        if (searchParam.getBrandId() != null && searchParam.getBrandId().size() > 0) {
            //根据品牌ID进行过滤
            boolQueryBuilder.filter(QueryBuilders.termsQuery("brandId", searchParam.getBrandId()));
        }
        //1.2 bool-filter - 过滤
        if (searchParam.getAttrs() != null && searchParam.getAttrs().size() > 0) {
            for (String paramAttr : searchParam.getAttrs()) {
                //根据所有指定属性进行过滤
                BoolQueryBuilder nestBoolQuery = QueryBuilders.boolQuery();
                String[] s = paramAttr.split("_");
                //检索属性ID
                String attrId = s[0];
                //属性检索值
                String[] attrValues = s[1].split(":");
                //根据attrId进行检索
                nestBoolQuery.must(QueryBuilders.termQuery("attrs.attrId", attrId));
                nestBoolQuery.must(QueryBuilders.termsQuery("attrs.attrValue", attrValues));
                //每种属性条件都放入到总的过滤中
                NestedQueryBuilder nestedQueryBuilder = QueryBuilders.nestedQuery("attrs", nestBoolQuery, ScoreMode.None);
                boolQueryBuilder.filter(nestedQueryBuilder);
            }
        }
        //1.2 bool-filter - 根据是否有库存进行过滤
        if (searchParam.getHasStock() != null) {
            boolQueryBuilder.filter(QueryBuilders.termsQuery("hasStock", searchParam.getHasStock() == 1));
        }
        //1.2 bool-filter - 过滤
        if (!StringUtils.isEmpty(searchParam.getSkuPrice())) {
            //根据价格区间进行过滤
            RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("skuPrice");
            String[] s = searchParam.getSkuPrice().split("_");
            if (s.length == 2) {
                //区间
                rangeQueryBuilder.gte(s[0]).lte(s[1]);
            } else if (s.length == 1) {
                //单个价格
                if (searchParam.getSkuPrice().startsWith("_")) {
                    //小于当前价格的
                    rangeQueryBuilder.lte(s[0]);
                }
                if (searchParam.getSkuPrice().endsWith("_")) {
                    //大于当前价格的
                    rangeQueryBuilder.gte(s[0]);
                }
            }
            boolQueryBuilder.filter(rangeQueryBuilder);
        }
        //查询条件构造
        searchSourceBuilder.query(boolQueryBuilder);

        /**
         * 完成排序、分页、高亮
         */
        //2.1 排序
        if (!StringUtils.isEmpty(searchParam.getSort())) {
            String sort = searchParam.getSort();
            String[] s = sort.split("_");
            SortOrder order = s[1].equalsIgnoreCase(SortOrder.ASC.toString()) ? SortOrder.ASC : SortOrder.DESC;
            searchSourceBuilder.sort(s[0], order);
        }
        //2.2 分页
        // from = (PageNum -1) * size
        searchSourceBuilder.from((searchParam.getPageNum() - 1) * EsConstant.PRODUCT_PAGESIZE);
        searchSourceBuilder.size(EsConstant.PRODUCT_PAGESIZE);
        //2.3 高亮
        if (!StringUtils.isEmpty(searchParam.getKeyWord())) {
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("skuTitle");
            highlightBuilder.preTags("<b style='color:red'>");
            highlightBuilder.postTags("</b>");
            searchSourceBuilder.highlighter(highlightBuilder);
        }
        /**
         * 聚合分析功能
         */
        //品牌聚合
        TermsAggregationBuilder brandAgg = AggregationBuilders.terms("brand_agg");
        brandAgg.field("brandId").size(50);
        //品牌聚合的子聚合
        brandAgg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
        brandAgg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));
        searchSourceBuilder.aggregation(brandAgg);
        //分类聚合
        TermsAggregationBuilder catalogAggregation = AggregationBuilders.terms("catalog_agg").field("catalogId").size(20);
        catalogAggregation.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1));
        searchSourceBuilder.aggregation(catalogAggregation);
        //属性聚合(嵌入式聚合)
        NestedAggregationBuilder nestedAggregationBuilder = AggregationBuilders.nested("attr_agg", "attrs");
        TermsAggregationBuilder idAgg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId");
        idAgg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));
        idAgg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(50));
        nestedAggregationBuilder.subAggregation(idAgg);
        searchSourceBuilder.aggregation(nestedAggregationBuilder);
        //查询请求
        SearchRequest searchRequest = new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, searchSourceBuilder);
        return searchRequest;

    }


    /**
     * 分析响应数据,封装成结果数据
     *
     * @param searchResponse 响应数据
     * @param searchParam    请求参数
     * @return 结果数据
     */
    private SearchResult buildSearchResponse(SearchResponse searchResponse, SearchParam searchParam) {
        SearchResult searchResult = new SearchResult();
        //获取查询结果
        SearchHits hits = searchResponse.getHits();
        //1. 返回的所有查询到的商品信息
        List<SkuEsModel> skuEsModelList = new ArrayList<>();
        if (hits.getHits() != null && hits.getHits().length > 0) {
            for (SearchHit hitsHit : hits.getHits()) {
                String sourceAsString = hitsHit.getSourceAsString();
                //转换成SkuEsModel 对象
                SkuEsModel skuEsModel = JSON.parseObject(sourceAsString, SkuEsModel.class);
                if (!StringUtils.isEmpty(searchParam.getKeyWord())) {
                    //设置高亮字段显示
                    HighlightField skuTitle = hitsHit.getHighlightFields().get("skuTitle");
                    String newSkuTitle = skuTitle.getFragments()[0].string();
                    skuEsModel.setSkuTitle(newSkuTitle);
                }
                skuEsModelList.add(skuEsModel);
            }
        }
        searchResult.setProducts(skuEsModelList);
        //2. 当前商品涉及到的所有属性信息
        List<SearchResult.AttrVo> attrVos = new ArrayList<>();
        ParsedNested attrAgg = searchResponse.getAggregations().get("attr_agg");
        ParsedLongTerms attrIdAgg = attrAgg.getAggregations().get("attr_id_agg");
        for (Terms.Bucket bucket : attrIdAgg.getBuckets()) {
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
            long attrId = bucket.getKeyAsNumber().longValue();
            String attrName = ((ParsedStringTerms) bucket.getAggregations().get("attr_name_agg")).getBuckets().get(0).getKeyAsString();
            List<String> attrValues = ((ParsedStringTerms) bucket.getAggregations().get("attr_value_agg")).getBuckets().stream().map(Terms.Bucket::getKeyAsString).collect(Collectors.toList());
            attrVo.setAttrId(attrId);
            attrVo.setAttrName(attrName);
            attrVo.setAttrValue(attrValues);
            attrVos.add(attrVo);
        }
        searchResult.setAttrs(attrVos);
        //3. 当前商品涉及到的品牌信息
        List<SearchResult.BrandVo> brandVos = new ArrayList<>();
        ParsedLongTerms brandAgg = searchResponse.getAggregations().get("brand_agg");
        for (Terms.Bucket bucket : brandAgg.getBuckets()) {
            SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
            long brandId = bucket.getKeyAsNumber().longValue();
            String brandImg = "";
            List<? extends Terms.Bucket> buckets = ((ParsedStringTerms) bucket.getAggregations().get("brand_img_agg")).getBuckets();
            if (buckets != null && buckets.size() > 0) {
                brandImg = buckets.get(0).getKeyAsString();
            }
            String brandName = ((ParsedStringTerms) bucket.getAggregations().get("brand_name_agg")).getBuckets().get(0).getKeyAsString();
            brandVo.setBrandId(brandId);
            brandVo.setBrandName(brandName);
            brandVo.setBrandImg(brandImg);
            brandVos.add(brandVo);
        }
        searchResult.setBrands(brandVos);
        //4.当前商品涉及到的分类信息
        List<SearchResult.CatalogVo> catalogVos = new ArrayList<>();
        ParsedLongTerms catalogAgg = searchResponse.getAggregations().get("catalog_agg");
        for (Terms.Bucket bucket : catalogAgg.getBuckets()) {
            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
            String keyAsString = bucket.getKeyAsString();
            //获取分类ID
            catalogVo.setCatalogId(Long.parseLong(keyAsString));
            //获取子聚合
            ParsedStringTerms catalogNameAgg = bucket.getAggregations().get("catalog_name_agg");
            String catalogName = catalogNameAgg.getBuckets().get(0).getKeyAsString();
            catalogVo.setCatalogName(catalogName);
            catalogVos.add(catalogVo);
        }
        searchResult.setCatalogs(catalogVos);

        //5.分页信息
        searchResult.setPageNum(searchParam.getPageNum());
        //总记录数
        long total = hits.getTotalHits().value;
        searchResult.setTotal(total);
        Integer totalPages = (int) total % EsConstant.PRODUCT_PAGESIZE == 0 ? (int) total / EsConstant.PRODUCT_PAGESIZE : ((int) total / EsConstant.PRODUCT_PAGESIZE + 1);
        searchResult.setTotalPages(totalPages);
        List<Integer> pageNavs = new ArrayList<>();
        for (Integer i = 1; i <= totalPages; i++) {
            pageNavs.add(i);
        }
        searchResult.setPageNavs(pageNavs);

        //6、构建面包屑导航
        if (searchParam.getAttrs() != null && searchParam.getAttrs().size() > 0) {
            List<SearchResult.NavVo> collect = searchParam.getAttrs().stream().map(attr -> {
                //1、分析每一个attrs传过来的参数值
                SearchResult.NavVo navVo = new SearchResult.NavVo();
                String[] s = attr.split("_");
                navVo.setNavValue(s[1]);
                R r = productFeignService.attrInfo(Long.parseLong(s[0]));
                if (r.getCode() == 0) {
                    AttrResVo data = r.getData("attr",new TypeReference<AttrResVo>(){});
                    navVo.setNavName(data.getAttrName());
                } else {
                    navVo.setNavName(s[0]);
                }

                //2、取消了这个面包屑以后，我们要跳转到哪个地方，将请求的地址url里面的当前置空
                //拿到所有的查询条件，去掉当前
                String encode = null;
                try {
                    encode = URLEncoder.encode(attr,"UTF-8");
                    encode = encode.replace("+","%20");  //浏览器对空格的编码和Java不一样，差异化处理
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                String replace = searchParam.getQueryString().replace("&attrs=" + encode, "");
                navVo.setLink("http://search.gulimallwolf.com/list.html?" + replace);
                return navVo;
            }).collect(Collectors.toList());

            searchResult.setNavs(collect);
        }
        return searchResult;
    }
}
